package com.mall.manager.authority.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.util.WebUtils;
import com.mall.common.entity.PowerInfo;
import com.mall.untils.Page;
/**
 * 角色权限列表信息
 * @author liugb
 * @date 2016 7 7
 */
@Service
@SuppressWarnings("unchecked")
public class PartPowerService {
	@Resource
    private JdbcTemplate jdbcTemplate;
	//日志信息
	private Logger logger = LoggerFactory.getLogger(PartPowerService.class);
	
	/**
	 * 角色权限列表信息分页方法
	 * @param request
	 * @return
	 */
	public Page manager_tpartpower_list(HttpServletRequest request) {
		Page page = null;
	    Map<String,Object> paraMap = WebUtils.getParametersStartingWith(request, "");
	    int pageNo = MapUtils.getIntValue(paraMap, "pageNo");
		String part_id = MapUtils.getString(paraMap, "part_id");
		String power_id = MapUtils.getString(paraMap, "power_id");
	    int pageSize = 10;
    	try {
 	        if (pageNo == 0){
 	        	pageNo = 1;
 	        }
 	        String sql = "select count(*) from t_part_power ";
 	        int total = this.jdbcTemplate.queryForObject(sql, Integer.class);
 	        int startIndex = Page.getStartOfPage(pageNo, pageSize);
 	        StringBuffer sb = new StringBuffer("select * from t_part_power where 1=1");
 	        if(!StringUtils.isEmpty(part_id)){
 	        	sb.append(" and part_id = " + part_id);
 	        }else if(!StringUtils.isEmpty(power_id)){
 	        	sb.append(" and power_id = "+ power_id);        	
 	        }
 	        sb.append(" order by id desc limit " + startIndex + "," + pageSize);
 	       List<Map<String, Object>>  queryForList = this.jdbcTemplate.queryForList(sb.toString());
 	        page = new Page(startIndex, total, pageSize, queryForList);
 	        return page;
 	    } catch (Exception e) {
 	        this.logger.info(e.toString());
 	        return null;
 	    }
	}
	
	/**
	 * 角色权限删除方法
	 * @param paraMap
	 * @return
	 */
	public int manager_del_tpartpower(Map<String, Object> paraMap) {
		int id = MapUtils.getIntValue(paraMap, "id");
		try {
			String sql="delete from t_part_power where id=?";
			int update = jdbcTemplate.update(sql,id);
			return update;
		} catch (Exception e) {
			return 0;
		}
	}
	/**
	 * 根据角色id删除
	 * @param paraMap
	 * @return
	 */
	public int manager_del_tpartpowerByRoleId(Map<String, Object> paraMap) {
		int id = MapUtils.getIntValue(paraMap, "roleId");
		try {
			String sql="delete from t_part_power where part_id=?";
			int update = jdbcTemplate.update(sql,id);
			return update;
		} catch (Exception e) {
			return 0;
		}
	}
	/**
	 * 角色权限修改方法
	 * @param paraMap
	 * @return
	 */
	public int manager_update_tpartpower(Map<String, Object> paraMap) {
	
		String part_id = MapUtils.getString(paraMap, "part_id");
		String power_id = MapUtils.getString(paraMap, "power_id");
		String id = MapUtils.getString(paraMap, "id");
		try {
			String sql = "update t_part_power set part_id=?,power_id=? where id = ?";
			int update = jdbcTemplate.update(sql,part_id,power_id,id);
			return update;
		} catch (Exception e) {
			return 0;
		}
	}
    /**
     * 角色权限添加数据
     * @param paraMap
     * @return
     */
	public int manager_insert_tpartpower(int part_id,int power_id) {
		try {
			String sql="insert into t_part_power(part_id,power_id,create_time,update_time) values(?,?,now(),now())";
			int update = jdbcTemplate.update(sql,part_id,power_id);
			return update;
		} catch (Exception e) {
			return 0;
		}
	}
	
	/**
	 * 根据用户ID，查询用户所拥有的权限
	 * @param userId 用户ID
	 * @return
	 */
	public List<PowerInfo> findRolePermission(Integer userId,Integer parentId,Integer level){
		String sql = "select * from t_power where id in(select power_id from t_part_power where part_id in(select part_id from t_user_part where user_id=?))";
		List<PowerInfo> power = new ArrayList<PowerInfo>();
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, userId);
		for(Map<String,Object> m:list){
			PowerInfo pi = new PowerInfo();
			pi.setId(MapUtils.getInteger(m, "id"));
			pi.setPartentId(MapUtils.getInteger(m, "parent_id"));
			pi.setName(MapUtils.getString(m, "name"));
			pi.setPowerAddr(MapUtils.getString(m, "poweraddr"));
			pi.setRemarks(MapUtils.getString(m, "remarks"));
			pi.setLevel(MapUtils.getInteger(m, "level"));
			power.add(pi);
		}
		return power;
	}
	
    /**
     * 查询权限类别
     * @param userPart
     * @return
     */
	public List<Map<String,Object>> findPartPower(Map<String,Object> userPart){
		  try{
  			  StringBuffer sql = new StringBuffer("select p.id,p.part_id,p.power_id,t.parent_id,t.poweraddr,t.name,t.level from t_part_power p,t_power t where p.power_id=t.id and p.part_id in(");
  			  JSONArray arr = JSONArray.fromObject(userPart);
  			  for(int i=0;i<arr.size();i++){
  				Map<String,Object> m = JSONObject.fromObject(arr.get(i));
  				sql.append(MapUtils.getInteger(m, "partId")).append(",");
  			  }
  			  sql.append("-1)");
			  return jdbcTemplate.queryForList(sql.toString());
		  }catch(Exception e){
			  logger.info("查询权限列表异常："+e.toString());
		  }
		  return null;
	  }
    /**
     * 根据角色id查询所拥有的权限
     * @param roleId
     * @return
     */
	public List<Map<String,Object>> findByRoleId(int roleId){
		String sql = "select * from t_part_power p where p.part_id = ?";
		List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql,roleId);
		
		return rs;
	}
}
